<?php
	error_reporting(0);
	header("Content-Type: text/Calendar");
	header("Content-Disposition: inline; filename=my_table.ics");

	echo "BEGIN:VCALENDAR\n";
	echo "PRODID:-//Google Inc//Google Calendar 70.9054//EN\n";
	echo "VERSION:2.0\n";
	echo "CALSCALE:GREGORIAN\n";
	echo "METHOD:PUBLISH\n";

	echo "BEGIN:VTIMEZONE\n";
	echo "TZID:Asia/Shanghai\n";
	echo "X-LIC-LOCATION:Asia/Shanghai\n";
	echo "BEGIN:STANDARD\n";
	echo "TZOFFSETFROM:+0800\n";
	echo "TZOFFSETTO:+0800\n";
	echo "TZNAME:CST\n";
	echo "DTSTART:19700101T000000\n";
	echo "END:STANDARD\n";
	echo "END:VTIMEZONE\n";


	include ('./src/connect.php');
	include ('./src/config.php');
	session_start();
	$username = $_SESSION['username'];

	$query = "SELECT * FROM ark_mytable WHERE uid='$username' ORDER BY weekday, dayfrom";

	if ($result = mysql_query($query, $link)) {
		while ($res = mysql_fetch_array($result)) {
			echo "BEGIN:VEVENT\n";

			$start = $weekday_to_date[$res['weekday']]." ".$dayfrom[$res['dayfrom']];
			$end = $weekday_to_date[$res['weekday']]." ".$dayto[$res['dayto']];

			echo "DTSTART;TZID=Asia/Shanghai:".date("Ymd\THis", strtotime($start))."\n";
			echo "DTEND;TZID=Asia/Shanghai:".date("Ymd\THis", strtotime($end))."\n";
			echo "RRULE:FREQ=WEEKLY;BYDAY=".$byday[$res['weekday']]."\n";
			echo "DTSTAMP:".date("Ymd\THis\Z")."\n";
			echo "UID:".rand()."@techos.3-a.net\n";
			echo "CREATED:".date("Ymd\THis\Z")."\n";
			echo "DESCRIPTION:$res[teacher]\n";
			echo "LAST-MODIFIED:".date("Ymd\THis\Z")."\n";
			echo "LOCATION:$res[campus]$resp[building]$res[room]\n";
			echo "SEQUENCE:0\n";
			echo "STATUS:CONFIRMED\n";
			echo "SUMMARY:$res[coursename]\n";
			echo "TRANSP:OPAQUE\n";
			echo "END:VEVENT\n";
		}
	}

	echo "END:VCALENDAR\n";
?>